package com.example.chamberlainserver.controller;

import com.example.chamberlainserver.Service.DashboardService;
import com.example.chamberlainserver.Vo.Request.Dashboard.DashboardQuery;
import com.example.chamberlainserver.Vo.Response.ApiResponse;
import com.example.chamberlainserver.Vo.Response.Dashboard.DashboardDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 数据大屏控制器
 */
@RestController
@RequestMapping("/dashboard")
public class DashboardController {

    @Autowired
    private DashboardService dashboardService;

    /**
     * 获取系统概览数据
     * @return 系统概览数据
     */
    @GetMapping("/system-overview")
    @PreAuthorize("hasRole('ADMIN') or hasRole('MANAGER')")
    public ApiResponse<DashboardDTO.SystemOverview> getSystemOverview() {
        return ApiResponse.success(dashboardService.getSystemOverview());
    }

    /**
     * 获取物资概览数据
     * @return 物资概览数据
     */
    @GetMapping("/material-overview")
    @PreAuthorize("hasRole('ADMIN') or hasRole('MANAGER')")
    public ApiResponse<DashboardDTO.MaterialOverview> getMaterialOverview() {
        return ApiResponse.success(dashboardService.getMaterialOverview());
    }

    /**
     * 获取用户活跃度数据
     * @param period 统计周期（day/week/month/year）
     * @return 用户活跃度数据
     */
    @GetMapping("/user-activity")
    @PreAuthorize("hasRole('ADMIN') or hasRole('MANAGER')")
    public ApiResponse<DashboardDTO.UserActivity> getUserActivity(
            @RequestParam(value = "period", defaultValue = "month") String period) {
        return ApiResponse.success(dashboardService.getUserActivity(period));
    }

    /**
     * 获取物资分类占比数据
     * @return 物资分类占比数据
     */
    @GetMapping("/category-ratio")
    @PreAuthorize("hasRole('ADMIN') or hasRole('MANAGER')")
    public ApiResponse<List<DashboardDTO.CategoryRatio>> getCategoryRatio() {
        return ApiResponse.success(dashboardService.getCategoryRatio());
    }



    /**
     * 获取物资使用排行数据
     * @param query 查询参数
     * @return 物资使用排行数据
     */
    @GetMapping("/material-usage-ranking")
    @PreAuthorize("hasRole('ADMIN') or hasRole('MANAGER')")
    public ApiResponse<List<DashboardDTO.MaterialUsage>> getMaterialUsageRanking(DashboardQuery query) {
        return ApiResponse.success(dashboardService.getMaterialUsageRanking(query));
    }

    /**
     * 获取库存不足物资数据
     * @param limit 限制返回数量
     * @return 库存不足物资数据
     */
    @GetMapping("/low-stock-materials")
    @PreAuthorize("hasRole('ADMIN') or hasRole('MANAGER')")
    public ApiResponse<List<DashboardDTO.LowStockMaterial>> getLowStockMaterials(
            @RequestParam(value = "limit", defaultValue = "10") Integer limit) {
        return ApiResponse.success(dashboardService.getLowStockMaterials(limit));
    }

    /**
     * 获取跳闸统计数据
     * @param period 统计周期（week/month/quarter/year）
     * @return 跳闸统计数据
     */
    @GetMapping("/tripping-stats")
    @PreAuthorize("hasRole('ADMIN') or hasRole('MANAGER')")
    public ApiResponse<DashboardDTO.TrippingStats> getTrippingStats(
            @RequestParam(value = "period", defaultValue = "month") String period) {
        return ApiResponse.success(dashboardService.getTrippingStats(period));
    }

    /**
     * 获取功率分布数据
     * @return 功率分布数据
     */
    @GetMapping("/power-distribution")
    @PreAuthorize("hasRole('ADMIN') or hasRole('MANAGER')")
    public ApiResponse<List<DashboardDTO.PowerDistribution>> getPowerDistribution() {
        return ApiResponse.success(dashboardService.getPowerDistribution());
    }

    /**
     * 获取时间分布数据
     * @param query 查询参数
     * @return 时间分布数据
     */
    @GetMapping("/time-distribution")
    @PreAuthorize("hasRole('ADMIN') or hasRole('MANAGER')")
    public ApiResponse<DashboardDTO.TimeDistribution> getTimeDistribution(DashboardQuery query) {
        return ApiResponse.success(dashboardService.getTimeDistribution(query));
    }

    /**
     * 获取班级排名数据
     * @param query 查询参数
     * @return 班级排名数据
     */
    @GetMapping("/class-ranking")
    @PreAuthorize("hasRole('ADMIN') or hasRole('MANAGER')")
    public ApiResponse<List<DashboardDTO.ClassRanking>> getClassRanking(DashboardQuery query) {
        return ApiResponse.success(dashboardService.getClassRanking(query));
    }

    /**
     * 获取登录统计数据
     * @param period 统计周期（week/month/quarter/year）
     * @return 登录统计数据
     */
    @GetMapping("/login-stats")
    @PreAuthorize("hasRole('ADMIN') or hasRole('MANAGER')")
    public ApiResponse<DashboardDTO.LoginStats> getLoginStats(
            @RequestParam(value = "period", defaultValue = "month") String period) {
        return ApiResponse.success(dashboardService.getLoginStats(period));
    }

    /**
     * 获取操作分布数据
     * @param period 统计周期（week/month/quarter/year）
     * @return 操作分布数据
     */
    @GetMapping("/operation-distribution")
    @PreAuthorize("hasRole('ADMIN') or hasRole('MANAGER')")
    public ApiResponse<List<DashboardDTO.OperationDistribution>> getOperationDistribution(
            @RequestParam(value = "period", defaultValue = "month") String period) {
        return ApiResponse.success(dashboardService.getOperationDistribution(period));
    }
    
    /**
     * 获取物资库存趋势数据
     * @param period 统计周期（daily/weekly/monthly）
     * @param days 统计天数（默认30天）
     * @return 物资库存趋势数据
     */
    @GetMapping("/material-stock-trend")
    @PreAuthorize("hasRole('ADMIN') or hasRole('MANAGER') or hasRole('BUTLER')")
    public ApiResponse<DashboardDTO.MaterialStockTrend> getMaterialStockTrend(
            @RequestParam(value = "period", defaultValue = "daily") String period,
            @RequestParam(value = "days", defaultValue = "30") Integer days) {
        try {
            DashboardDTO.MaterialStockTrend result = dashboardService.getMaterialStockTrend(period, days);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(500, "获取库存趋势数据失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取指定物资的库存趋势详情
     * @param materialId 物资ID
     * @param period 统计周期（daily/weekly/monthly）
     * @param days 统计天数（默认30天）
     * @return 物资库存趋势详情
     */
    @GetMapping("/material-stock-trend/{materialId}")
    @PreAuthorize("hasRole('ADMIN') or hasRole('MANAGER') or hasRole('BUTLER')")
    public ApiResponse<DashboardDTO.MaterialStockTrendDetail> getMaterialStockTrendDetail(
            @PathVariable Long materialId,
            @RequestParam(value = "period", defaultValue = "daily") String period,
            @RequestParam(value = "days", defaultValue = "30") Integer days) {
        try {
            DashboardDTO.MaterialStockTrendDetail result = dashboardService.getMaterialStockTrendDetail(materialId, period, days);
            return ApiResponse.success(result);
        } catch (IllegalArgumentException e) {
            return ApiResponse.error(400, e.getMessage());
        } catch (Exception e) {
            return ApiResponse.error(500, "获取物资库存趋势详情失败: " + e.getMessage());
        }
    }
}